package upm.pb4agent.team5.common;

import upm.pb4agent.ontology.SubscribeReferee;
import jade.content.Concept;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

public class BRefereeManageMessages extends CyclicBehaviour {
	private static final long serialVersionUID = 4257237506900906176L;
	
	private Referee referee = null;

	public BRefereeManageMessages(Referee referee) {
		this.referee = referee;
	}
	
	public void action() {
		ACLMessage msg = referee.blockingReceive();

		try {
			if (msg.getPerformative() == ACLMessage.SUBSCRIBE) {
				@SuppressWarnings("unused")
				SubscribeReferee subscription = (SubscribeReferee) referee.getConcept(msg); // Just casting is enough, if fails goto catch
				referee.subscribe(msg.getSender()); // Adding listener (subscribe)
				
				// Replying subscription AGREE
				referee.send(msg.getSender(), ACLMessage.AGREE, SubscribeReferee.class.getSimpleName());
				
				System.out.println(referee.getLocalName() + ": Subscription accepted for " + msg.getSender().getLocalName());		
			} else if (msg.getPerformative() == ACLMessage.CANCEL) {
				referee.unsubscribe(msg.getSender()); // Removing listener (unsubscribe)				
				System.out.println(referee.getLocalName() + ": Subscription cancelled for " + msg.getSender().getLocalName());		

			} else { // Messages from the watcher (or plattform)
				Concept concept = referee.getConcept(msg);
				new Thread(new RefereeSendMessage(referee, concept)).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(referee.getLocalName() + ": Problem receiving message");
		}
	}
	

	
}

